package com.hanserwei.han_picture.controller;

import com.hanserwei.han_picture.annotation.AuthCheck;
import com.hanserwei.han_picture.constant.UserConstant;
import com.hanserwei.han_picture.domain.common.ApiResponse;
import com.hanserwei.han_picture.domain.exception.ApiException;
import com.hanserwei.han_picture.enums.ResponseCodeEnum;
import com.hanserwei.han_picture.manager.CosManager;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Slf4j
@Tag(name = "FileUploadControllerTesting")
@RestController
@RequiredArgsConstructor
@RequestMapping("/file")
public class FileController {

    private final CosManager cosManager;

    @Operation(summary = "上传文件")
    @PostMapping("/upload/test")
    @AuthCheck(requiredRole = UserConstant.ADMIN_ROLE)
    public ApiResponse<String> uploadFileTest(@RequestPart("file") MultipartFile multipartFile) {
        // 1.拼接文件路径，构造文件夹
        String originalFilename = multipartFile.getOriginalFilename();
        String filePath = String.format("/test/%s", originalFilename);
        File file = null;
        try {
            // 创建临时文件，前缀为filePath，后缀为.tmp
            file = File.createTempFile(filePath, null);
            // 将multipartFile写入临时文件
            multipartFile.transferTo(file);
            // 上传文件到COS
            cosManager.putObject(filePath, file);
            return ApiResponse.success("上传成功", filePath);
        } catch (Exception e) {
            log.error("创建临时文件失败", e);
            throw new ApiException(ResponseCodeEnum.SYSTEM_ERROR, "上传文件失败");
        } finally {
            // 删除临时文件
            if (file != null) {
                boolean deleted = file.delete();
                if (!deleted) {
                    log.error("删除临时文件失败");
                }
            }
        }
    }

    @Operation(summary = "文件下载")
    @PostMapping("/download/test")
    @AuthCheck(requiredRole = UserConstant.ADMIN_ROLE)
    public ResponseEntity<byte[]> downloadFileTest(String filePath, HttpServletResponse response) {
        COSObjectInputStream cosObjectInput = null;
        try {
            // 获取文件
            COSObject cosObject = cosManager.getObject(filePath);
            cosObjectInput = cosObject.getObjectContent();
            // 处理下载的流
            byte[] bytes = IOUtils.toByteArray(cosObjectInput);
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDisposition(ContentDisposition.attachment().filename(filePath).build());

            // 返回文件流
            return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            log.error("下载文件失败", e);
            throw new ApiException(ResponseCodeEnum.SYSTEM_ERROR, "下载文件失败");
        } finally {
            if (cosObjectInput != null) {
                try {
                    cosObjectInput.close();
                } catch (IOException e) {
                    log.error("关闭输入流失败", e);
                }
            }
        }
    }
}
